﻿package{
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.net.Responder;
	
	public class Remoting_handler extends EventDispatcher {
		
		
		private var _names:Array;
		private var target:Sprite; 
		private var objectEncoding;
		private var myConnection:NetConnection;
		private var staWidth:Number;
		
		private var objData:Object;
		public var loadObj:Loader;
		private  var objDataContainer:Sprite;
		
		
		private var gatewayUrl:String = "http://dd.ourvfs.com/dd10vincent/amfphp/gateway.php";
		
		public function Remoting_handler(target):void {
			//trace(stWidth);
			objectEncoding = ObjectEncoding.AMF0;
			// Connect to gateway
			myConnection = new NetConnection();
			myConnection.connect(gatewayUrl);
			this.target = target;
		
		}
		
		//Gets all names and their id's.	
		public function getNodes():void
		{
			var responder:Responder = new Responder(handleGetNodes, handleRemotingError);
			myConnection.call("Pman_remote_v1.getNames", responder);
		}
		
		private function handleGetNodes(re:Object):void {
			//trace("handleGetNames");
			var result:Object = this.deserialize(re);
			var tree:TreeBuilder = new TreeBuilder()
			target.addChild(tree);
			
			//trace(result);
			var ill:Number = result.length;
			var nodeWsum:Number = 0;
			var nodeSpace:Number = 0;
			for(var x:Number = 0; x < ill; x++){
				
				var objIn:Object_instansiator = new Object_instansiator(result[x], x, staWidth)
				objIn.name = "title" + x;
				nodeWsum = target.width/(ill/objIn.width);
				target.parent.addChild(objIn);
				trace("result[i].id: " + result[x].id + " : " + result[x].title + ", parent_id: " + result[x].parent_id);				
			};
				nodeSpace = nodeWsum/(ill+1);
			
		}
		
		private function handleRemotingError( fault:Object ):void {
			trace("Remoting error");
		}
		
		private function deserialize(result:Object){
			var rows:Number = result.serverInfo.totalCount//how many rows are in our recordset?
			var resultArray:Array = [];
			var columnNames:Array = String(result.serverInfo.columnNames).split(",");
			var data:Array = String(result.serverInfo.initialData).split(",");
			for(var i:Number = 0; i<rows; i++){
				var temp = {};
				//trace(columnNames);
				for(var x:Number = 0;x<columnNames.length;x++){
					temp[columnNames[x]] = data[(i*columnNames.length)+x];
				}
				resultArray.push(temp);
			}
			return resultArray;
		}
		
		
		
		
		
	}
}